<?php
	require_once('config.class.php');
	
	/**
	 * The user access control class helps to handle the
	 * current user's permissions.
	 */
	class UserAccessControl {
		/**
		 * Initializes a new instance of the UserAccessControl class.
		 */
		public function __construct() {
			session_start();
		}
		
		/**
		 * Finds out whether the current user is a moderator
		 * 
		 * @return bool TRUE if the current user is a moderator; otherwise FALSE.
		 */
		public function isMod() {
			if (isset($_SESSION['mod'])) {
				if ('true' === $_SESSION['mod']) return true;
			}
			return false;
		}
		
		/**
		 * Tests whether the current user is a moderator and redirects
		 * him/her to login.php if (s)he is not.
		 * 
		 * @return void
		 */
		public function grantAccessOnlyForMods() {
			if (!$this->isMod()) {
				$_SESSION['gotoafterlogin'] = basename($_SERVER['PHP_SELF']);
				header('HTTP/1.1 307 Moved temporarily');
				UserAccessControl::redirectToLocalTarget('login.php');
			}
		}
		
		/**
		 * Tests whether the given $password matches the password
		 * which is set in our Config file and saves the result
		 * in the $_SESSION, so that in can be used in other parts
		 * of the program.
		 */
		public function grantModAccess($password) {
			$config = new Config();
			if ($config->getModPassword() === $password) {
				$_SESSION['mod'] = 'true';
				header('HTTP/1.1 307 Moved temporarily');
				UserAccessControl::redirectToLocalTarget($_SESSION['gotoafterlogin']);
			}
		}
		
		/**
		 * Removes the current users moderator access from
		 * his/her $_SESSION. 
		 */
		public function removeModAccess() {
			$_SESSION['mod'] = 'false';
		}
		
		/**
		 * Tries to redirect this to a local target.
		 * This needs to be done as the HTTP Location header must contain an absolute URI. 
		 * 
		 * @access private
		 * @param string $target The local target. eg. 'login.php'
		 * @return void As this function causes the script to exit, it does not return anything.
		 * @copyright http://php.net/header
		 * @link http://php.net/header Most of this was taken from the official PHP documentation.
		 */
		private static function redirectToLocalTarget($target) {
			$host = $_SERVER['HTTP_HOST'];
			$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
			$extra = rawurlencode($target);
			header('Location: http://'. $host . $uri . '/' . $extra);
			exit;
		}
	}